package cn.itcast.service;

import cn.itcast.entity.PageResult;
import cn.itcast.entity.QueryPageBean;
import cn.itcast.mapper.CheckGroupMapper;
import cn.itcast.pojo.CheckGroup;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 检查组服务
 */

@Service(interfaceClass = CheckGroupService.class)
@Transactional
public class CheckGroupServiceImpl implements CheckGroupService {


    @Autowired
    private CheckGroupMapper checkGroupMapper;

    @Override
    public void add(CheckGroup checkGroup, Integer[] checkitemIds) {
        //新增检查组
        checkGroupMapper.add(checkGroup);
        //设置检查项和检查组的多对多关系
        Integer checkGroupId = checkGroup.getId();
        //调用插入关系表数据方法
        setCheckGroupAndCheckItem(checkGroupId,checkitemIds);

    }

    public void setCheckGroupAndCheckItem (Integer checkGroupId,Integer[] checkitemIds){
        if (checkitemIds != null && checkitemIds.length > 0){
            for (Integer checkitemId : checkitemIds) {
                Map<String,Integer> map = new HashMap<>();
                map.put("checkGroupId",checkGroupId);
                map.put("checkitemId",checkitemId);
                checkGroupMapper.setCheckGroupAndCheckItem(map);
            }
        }
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        //使用mybaties插件助手
        PageHelper.startPage(currentPage, pageSize);
        Page<CheckGroup> page =checkGroupMapper.findPage(queryString);
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public CheckGroup findById(Integer id) {
       CheckGroup checkGroup = checkGroupMapper.findById(id);
       return checkGroup;
    }

    @Override
    public List<Integer> findCheckItemIdsByCheckGroupId(Integer id) {
        List<Integer> ids = checkGroupMapper.findCheckItemIdsByCheckGroupId(id);
        return ids;
    }

    @Override
    public void edit(CheckGroup checkGroup, Integer[] checkitemIds) {
        //更新基本数据
        checkGroupMapper.editCheckGroup(checkGroup);

        //删除原有关系表数据
        checkGroupMapper.deletecheckitemIds(checkGroup.getId());

        //添加更改的关系表数据
        setCheckGroupAndCheckItem(checkGroup.getId(),checkitemIds);

    }

    @Override
    public void delete(Integer id) {
        checkGroupMapper.deletecheckitemIds(id);
        checkGroupMapper.deleteCheckGroup(id);
    }

    @Override
    public List<CheckGroup> findAll() {
        return checkGroupMapper.findAll();

    }


}
